const router = require("koa-router")();
const {
  userRegister,
  userLogin,
  getUserinfo,
} = require("../control/userControls");
const { SuccessModel, ErrorModel } = require("../messageModel/index");
const loginCheck = require("../middleware/loginCheck");

router.prefix("/api/user");

//用户注册
router.post("/register", async function (ctx, next) {
  const { username, password } = ctx.request.body;
  try {
    const res = await userRegister(username, password);
    if (res) {
      ctx.body = new SuccessModel(res);
    }
  } catch (error) {
    console.error(error);
    ctx.body = new ErrorModel(-1, `注册失败${error.message}`);
  }
});

//用户登录
router.post("/login", async (ctx, next) => {
  const { username, password } = ctx.request.body;
  const res = await userLogin(username, password);
  if (res) {
    ctx.session.userInfo = res;
    ctx.body = new SuccessModel(username);
  } else {
    ctx.body = new ErrorModel(-1, `登录失败`);
  }
});

//用户更新
router.get("/userinfo", loginCheck, async (ctx, next) => {
  const { username } = ctx.session.userInfo;
  const res = await getUserinfo(username);
  if (res) {
    ctx.body = new SuccessModel(res);
  } else {
    ctx.body = new ErrorModel("获取用户信息失败");
  }
});

module.exports = router;
